﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BgCtr : MonoBehaviour {
    public GameObject gm;
    public GameObject bg;
    public float maxDistance;
    private GameObject mainBall;

    Vector3 gravityDirection;
    float mainBallDistance;

	// Use this for initialization
	void Start () {
        mainBall = gm.GetComponent<MainBallCtr>().mainBall;
        mainBallDistance = Vector3.Distance(mainBall.GetComponent<RectTransform>().anchoredPosition3D, Vector3.zero);
        gravityDirection = -mainBall.GetComponent<RectTransform>().anchoredPosition3D / mainBallDistance;
    }
	
	// Update is called once per frame
	void Update () {
        if (GameCtr.isPause == false)
        {
            moveBg();
        }
	}

    void moveBg()
    {
        RectTransform rectTransform = mainBall.GetComponent<RectTransform>();
        mainBallDistance = Vector3.Distance(rectTransform.anchoredPosition3D, Vector3.zero);
        gravityDirection = -rectTransform.anchoredPosition3D / mainBallDistance;

        if (mainBallDistance >= maxDistance)
        {
            Vector3 dstPos = (mainBallDistance - maxDistance) * gravityDirection;           

            float temp = 1.0f - (mainBallDistance - maxDistance) / (8.0f * maxDistance);
            if(temp < 0.5f)
            {
                temp = 0.5f;
            }
            bg.transform.localScale = new Vector3(temp, temp);

            bg.transform.localPosition = dstPos * temp;
        }
        else
        {
            bg.transform.localScale = new Vector3(1.0f, 1.0f);
        }
    }

    public IEnumerator OnShakeBG()
    {
        Vector3 vector = mainBall.GetComponent<RectTransform>().anchoredPosition3D;
        for (int i = 0; i < 2; i++)
        {
            bg.transform.position -= vector.normalized * GameCtr.bgShakeMultiple;
            yield return null;
            yield return null;
            bg.transform.position += vector.normalized * GameCtr.bgShakeMultiple;
            yield return null;
            yield return null;
        }
    }
}
